import apiClient from './client'
import type { Task, TaskExecution } from '@/types/task'
import type { TaskLog } from '@/types/log'
import type { Settings } from '@/types/settings'
import type { SystemInfo } from '@/types/system'
import { isSuccess } from '@/types/api'
import type { APIResponse } from '@/types/api'
import { message } from 'ant-design-vue'

// 统一的响应处理函数
function handleResponse<T>(response: APIResponse<T>, showError: boolean = true): T {
  if (isSuccess(response)) {
    // 如果data为null或undefined，根据类型提供默认值
    if (response.data === null || response.data === undefined) {
      // 对于void类型，返回undefined
      if (typeof response.data === 'undefined') {
        return undefined as T
      }
      // 对于数组类型，返回空数组
      return [] as T
    }
    return response.data!
  } else {
    if (showError) {
      message.error(response.msg || '请求失败')
    }
    throw new Error(response.msg || '请求失败')
  }
}

// 任务相关API
export const taskAPI = {
  // 获取任务列表
  async getTasks(): Promise<Task[]> {
    try {
      const res = await apiClient.get<APIResponse<Task[]>>('/tasks')
      const result = handleResponse(res.data)
      // 确保返回的是数组
      return Array.isArray(result) ? result : []
    } catch (error) {
      console.error('API getTasks error:', error)
      // 网络错误或其他错误时返回空数组
      return []
    }
  },

  // 创建任务
  async createTask(task: Omit<Task, 'id' | 'createdAt' | 'updatedAt'>): Promise<Task> {
    const res = await apiClient.post<APIResponse<Task>>('/tasks', task)
    return handleResponse(res.data)
  },

  // 更新任务
  async updateTask(id: string, task: Partial<Task>): Promise<Task> {
    const res = await apiClient.put<APIResponse<Task>>(`/tasks/${id}`, task)
    return handleResponse(res.data)
  },

  // 删除任务
  async deleteTask(id: string): Promise<void> {
    const res = await apiClient.delete<APIResponse<void>>(`/tasks/${id}`)
    handleResponse(res.data)
  },

  // 切换任务状态
  async toggleTask(id: string): Promise<Task> {
    const res = await apiClient.post<APIResponse<Task>>(`/tasks/${id}/toggle`)
    return handleResponse(res.data)
  },

  // 获取任务详情
  async getTask(id: string): Promise<Task> {
    const res = await apiClient.get<APIResponse<Task>>(`/tasks/${id}`)
    return handleResponse(res.data)
  },

  // 立即执行任务
  async executeTask(id: string): Promise<{ success: boolean; executionId: string; message?: string }> {
    const res = await apiClient.post<APIResponse<{ success: boolean; executionId: string; message?: string }>>(`/tasks/${id}/execute`)
    return handleResponse(res.data)
  },

  // 停止正在运行的任务
  async stopTask(id: string): Promise<{ success: boolean; message?: string }> {
    const res = await apiClient.post<APIResponse<{ success: boolean; message?: string }>>(`/tasks/${id}/stop`)
    return handleResponse(res.data)
  },

  // 获取执行记录
  async getExecution(executionId: string): Promise<TaskExecution> {
    const res = await apiClient.get<APIResponse<TaskExecution>>(`/tasks/executions/${executionId}`)
    return handleResponse(res.data)
  },

  // 切换任务置顶状态
  async togglePinTask(id: string): Promise<Task> {
    const res = await apiClient.post<APIResponse<Task>>(`/tasks/${id}/toggle-pin`)
    return handleResponse(res.data)
  }
}

// 日志相关API
export const logAPI = {
  // 获取执行日志
  async getLogs(params?: {
    taskId?: string
    status?: string
    startDate?: string
    endDate?: string
    page?: number
    pageSize?: number
  }): Promise<{
    logs: TaskLog[]
    total: number
  }> {
    const res = await apiClient.get<APIResponse<{ logs: TaskLog[]; total: number }>>('/logs', { params })
    return handleResponse(res.data)
  },

  // 获取特定任务的日志
  async getTaskLogs(taskId: string): Promise<TaskLog[]> {
    const res = await apiClient.get<APIResponse<TaskLog[]>>(`/logs/tasks/${taskId}`)
    return handleResponse(res.data)
  },

  // 清理过期日志
  async cleanupLogs(): Promise<{ deleted: number; cutoff: string }> {
    const res = await apiClient.post<APIResponse<{ deleted: number; cutoff: string }>>('/logs/cleanup')
    return handleResponse(res.data)
  }
}

// 设置相关API
export const settingsAPI = {
  // 获取系统设置
  async getSettings(): Promise<Settings> {
    const res = await apiClient.get<APIResponse<Settings>>('/settings')
    return handleResponse(res.data)
  },

  // 更新系统设置
  async updateSettings(settings: Partial<Settings>): Promise<Settings> {
    const res = await apiClient.put<APIResponse<Settings>>('/settings', settings)
    return handleResponse(res.data)
  },

  // 获取系统信息
  async getSystemInfo(): Promise<SystemInfo> {
    const res = await apiClient.get<APIResponse<SystemInfo>>('/system/info')
    return handleResponse(res.data)
  }
}

// 认证相关API (不需要token)
export const authAPI = {
  // 获取密码盐值
  async getSalt(): Promise<{ salt: string }> {
    const res = await apiClient.get<APIResponse<{ salt: string }>>('/auth/salt')
    return handleResponse(res.data)
  },

  // 用户登录
  async login(username: string, password: string): Promise<{ token: string }> {
    const res = await apiClient.post<APIResponse<{ token: string }>>('/auth/login', { username, password })
    return handleResponse(res.data)
  },

  // 修改密码 (需要token)
  async changePassword(oldPassword: string, newPassword: string): Promise<void> {
    try {
      const res = await apiClient.post<APIResponse<void>>('/auth/change-password', 
        { oldPassword, newPassword },
        { 
          // @ts-ignore - 自定义配置，用于控制错误提示
          __skipErrorMessage: true 
        }
      )
      
      // 直接处理响应，不使用handleResponse避免类型问题
      const response = res.data as APIResponse<void>
      if (!isSuccess(response)) {
        throw new Error(response.msg || '请求失败')
      }
    } catch (error: any) {
      // 如果是axios错误，保留原始错误信息
      if (error.response) {
        // 重新抛出原始错误，让组件能够访问response.data
        throw error
      } else {
        // 其他类型的错误，直接抛出
        throw error
      }
    }
  }
}

// 导出默认的API客户端
export default apiClient 